<?php

declare(strict_types=1);

namespace app\wechat\controller\admin;

use think\Request;
use think\Response;
use think\facade\Db;
use sheep\controller\Backend;
use app\wechat\facade\Wechat;
use app\wechat\model\Material as MaterialModel;
use sheep\exception\SheepException;

class Material extends Backend
{

    protected $wechat = null;
    protected $model = null;

    public function initialize()
    {
        $this->wechat = Wechat::officialAccount();
        $this->model = new MaterialModel;
    }
    /**
     * 素材列表
     *
     * @return Response
     */
    public function list(): Response
    {
        $list_rows = intval($this->request->param('list_rows', 10));
        $page = intval($this->request->param('page', 1));
        $type = $this->request->param('type', 'news');
        $offset = intval(($page - 1) * $list_rows);

        if(in_array($type, ['text', 'link'])) {
            $data = $this->model->sheepFilter()->where('type', $type)->paginate((int)request()->param('list_rows', 10));
        }else {
            // 使用微信远程素材列表
            $res = $this->wechat->material->list($type, $offset, $list_rows);
            if(!empty($res['errcode'])) {
                return error($res['errmsg']);
            }
            $data = [
                'current_page' => $page,
                'data' => $res['item'],
                'last_page' => intval(ceil($res['total_count'] / $list_rows)),
                'per_page' => $list_rows,
                'total' => intval($res['total_count']),
            ];
        }
        return success('获取成功', $data);
    }

    /**
     * 素材详情
     *
     * @param  int $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $data = $this->model->findOrFail($id);
        return success('获取成功', $data);
    }


    /**
     * 添加素材
     *
     * @return \think\Response
     */
    public function add()
    {
        $params = $this->request->only(['type', 'content']);

        if($params['type'] === 'text') {
            $params['content'] =  urldecode($params['content']);
        }

        // 参数校验
        // $this->svalidate($params, '.add');

        $material = Db::transaction(function () use ($params) {
            $material = $this->model->save($params);
            return $material;
        });
        return success('保存成功', $material);
    }

    /**
     * 编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $material = $this->model->findOrFail($id);
        $params = $this->request->only(['type', 'content']);
        if($params['type'] === 'text') {
            $params['content'] =  urldecode($params['content']);
        }

        // 参数校验
        // $this->svalidate($params);

        $material = Db::transaction(function () use ($params, $material) {
            $material->save($params);
            return $material;
        });

        return success('更新成功');
    }

    /**
     * 删除
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $is_real = $this->request->param('is_real', 0);
        Db::transaction(function () use ($id, $is_real) {
            $material = $this->model->findOrFail($id);
            if ($is_real) {
                $material->force()->delete();
            } else {
                $material->delete();
            }
        });

        return success('删除成功');
    }

    /**
     * 菜单列表
     *
     * @return Response
     */
    public function select(): Response
    {
        $list_rows = intval($this->request->param('list_rows', 10));
        $page = intval($this->request->param('page', 1));
        $type = $this->request->param('type', 'news');
        $offset = intval(($page - 1) * $list_rows);

        if(in_array($type, ['text', 'link'])) {
            $data = $this->model->where('type', $type)->order('id desc')->paginate((int)request()->param('list_rows', 10));
        }else {
            // 使用微信远程素材列表
            $res = $this->wechat->material->list($type, $offset, $list_rows);
            if(!empty($res['errcode'])) {
                return error($res['errmsg']);
            }
            $data = [
                'current_page' => $page,
                'data' => $res['item'],
                'last_page' => intval(ceil($res['total_count'] / $list_rows)),
                'per_page' => $list_rows,
                'total' => intval($res['total_count']),
            ];
        }
        return success('获取成功', $data);
    }
}
